<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

/**
 * 摇号批次管理
 * Class nianshenBatchController
 * @package Admin\Controller
 */
class NianshenBatchController extends BaseController {

    //控制器名称
    public static $name = "年审";
    public static $model = "nianshen";

    /**
     * 系统管理 -> 系统管理 -> 单位信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出单位信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("nianshen_batch")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->display();
    }

    public function fn_GenerateYears(){
        $year = intval(date("Y"));
        return array($year, $year+1);
    }

    /**
     * 单位信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $batch = M("nianshen_batch")->where(array("id"=>$dataId))->find();
        $this->assign("batch", $batch);

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        $this->display();
    }

    /**
     * 单位信息维护 -> 新增
     */
    public function add(){
        if(IS_POST){    //添加公司信息
            $data = array(
                "name" => I("post.name"),
                "year" => I("post.year"),
                "remarks" => I("post.remarks"),
                "ctime" => date("Y/m/d"),
                "cuser" => session("username"),
            );
            $dataId = M("nianshen_batch")->add($data);
            if($dataId){
                header("Location:/admin/nianshenBatch/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建公司信息失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $batch = M("nianshen_batch")->where(array("id"=>I("get.id")))->find();
            $this->assign("batch", $batch);
        }
        $this->assign("year", $this->fn_GenerateYears());
        $this->display();
    }

    public function loading(){
        $year = I("get.year");
        $this->assign("year", $year);
        $this->display();
    }

    public function ajax_endNS(){
        $year = I("post.year");
        if(!$year){
            $this->error("缺少必要参数");
        }
        $data = array("year"=>$year, "state"=>"已结束", "utime"=>time());
        $res = M("nianshen_batch")->where(array("year"=>$year))->save($data);
        if(!$res){
            $this->error("系统错误，结束年审失败");
        }
        $this->success();
    }

    public function ajax_startNS(){
        $year = I("post.year");
        if(!$year){
            $this->error("缺少必要参数");
        }
        $trans = M();
        $trans->startTrans();   // 开启事务
        try {
            $res = M("nianshen_batch")->where(array("state"=>"已启动"))->find();
            if($res){
                $this->error("操作失败，尚有年审处于启动状态中");
            }

            $totalLzf = $this->action_LzfNS($year);
            $totalGzf = $this->action_GzfNS($year);
            $total = $totalLzf + $totalGzf;
            $data = array(
                "state" => "已启动",
                "num" => $total
            );
            $res = M("nianshen_batch")->where(array("year"=>$year))->save($data);
            if(!$res){
                $this->error("系统错误，更新批次信息异常");
            }
            $trans->commit();   // 提交事务
            $this->success($total);
        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function action_LzfNS($year){
        $offset = 0;
        $pageNum = 100;
        $total = $this->fn_GetTotalNS("lzf");
        while($offset<$total){
            $list = $this->fn_GetNSData("lzf", $offset, $pageNum);
            foreach($list as $item){
                $data = array(
                    "no" => $this->fn_GenerateNSNo(),
                    "year" => $year,
                    "type" => "廉租房",
                    "dibaork" => $item['dibaork'],
                    "name" => $item['name'],
                    "idno" => $item['idno'],
                    "phone" => $item['phone'],
                    "yw_no" => $item['no'],
                    "community" => $item['community'],
                    "house_no" => $item['house_no'],
                    "house_addr" => $item['house_addr'],
                    "contact_no" => $item['contact_no'],
                    "state" => "审核中",
                    "ctime" => time(),
                    "cuser" => session("username")
                );
                //创建年审申请
                $res = M("nianshen")->add($data);
                if(!$res){
                    //$this->error(M("nianshen")->getLastSql());
                    $this->error("无法生成年审数据3");
                }

                $res2 = $this->fn_AddLhcsMarriageApply("lzf", $data['no'], $item);
                if(!$res2){
                    $this->error("无法生成年审数据2");
                }
            }
            $offset += $pageNum;
        }
        return $total;
    }

    protected function fn_AddLhcsMarriageApply($model, $nsNo, $apply){
        $lhsp = array(
            "spdw" => "婚姻登记处",
            "type" => self::$name,
            "model" => self::$model,
            "no" => $nsNo,
            "name" => $apply["name"],
            "marriage" => $apply["marriage"],
            "gender" => $apply["gender"],
            "idno" => $apply["idno"],
            "area_id" => $apply["area_id"],
            "phone" => $apply["phone"],
            "dibaork" => $apply["dibaork"],
            "dibaohm" => $apply["dibaohm"],
            "income" => $apply["income"],
            "estate" => $apply["estate"],
            "sqtime" => time(),
        );
        $peiou = $this->fn_GetPeiOuInfo($model, $apply['no']);
        if($peiou){
            $lhsp['name2'] = $peiou['name'];
            $lhsp['idno2'] = $peiou['idno'];
            $lhsp['gender2'] = $peiou['gender'];
            $lhsp['phone2'] = $peiou['phone'];
        }
        return M("lhsp")->add($lhsp);
    }

    public function fn_GetPeiOuInfo($model, $no){
        $where = array($model."_no"=>$no, "relation"=>"配偶");
        return M($model."_family")->field("name,idno,gender,phone")->where($where)->find();
    }

    public function action_GzfNS($year){
        $offset = 0;
        $pageNum = 100;
        $total = $this->fn_GetTotalNS("gzf");
        while($offset<$total){
            $list = $this->fn_GetNSData("gzf", $offset, $pageNum);
            foreach($list as $item){
                $data = array(
                    "no" => $this->fn_GenerateNSNo(),
                    "year" => $year,
                    "type" => "公租房",
                    "dibaork" => $item['dibaork'],
                    "name" => $item['name'],
                    "idno" => $item['idno'],
                    "phone" => $item['phone'],
                    "yw_no" => $item['no'],
                    "community" => $item['community'],
                    "house_no" => $item['house_no'],
                    "house_addr" => $item['house_addr'],
                    "contact_no" => $item['contact_no'],
                    "state" => "审核中",
                    "ctime" => time(),
                    "cuser" => session("username")
                );
                //创建年审申请
                $res = M("nianshen")->add($data);
                if(!$res){
                    $this->error("无法生成年审数据3");
                }

                $res2 = $this->fn_AddLhcsMarriageApply("gzf", $data['no'], $item);
                //$this->error(M("lhsp")->getLastSql());
                if(!$res2){
                    $this->error("无法生成年审数据4");
                }
            }
            $offset += $pageNum;
        }
        return $total;
    }

    private function fn_GenerateNSNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("nianshen_no")->add($data);
        return "N".$no;
    }

    public function fn_GetNSData($model, $offset, $pageNum){
        return M($model." m")
            ->field("m.*")
            ->join(C("DB_PREFIX")."house h on h.name=m.house_no", "LEFT")
            ->where(array("m.state"=>"done", "h.req_nianshen"=>"是"))->order("id asc")->limit($offset.",".$pageNum)->select();
    }

    public function fn_GetTotalNS($model){
        return M($model." m")
            ->join(C("DB_PREFIX")."house h on h.name=m.house_no", "LEFT")
            ->where(array("m.state"=>"done", "h.req_nianshen"=>"是"))->count();
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        //判断是否有已启动的年审批次
        $map["id"] = array("in", $dataIds);
        $data = M("nianshen_batch")->where($map)->select();
        foreach ($data as $item) {
            if($item['state']!='未启动'){
                $this->error("操作失败，不能删除已启动的年审批次信息");
            }
        }

        $res = M("nianshen_batch")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("nianshen_batch")->where(array("id" => $id))->find();
        if($res && $res['state']!='未启动'){
            $this->error("操作失败，不能删除已启动的年审批次信息");
        }

        $res = M("nianshen_batch")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("操作失败，无法删除该记录");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("nianshen_batch")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array();
        if(I("request.value")){
            $where[I("request.field")] = array("like", "%".I("request.value")."%");
        }
        return $where;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("nianshen_batch")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("nianshen_batch")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("nianshen_batch")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("nianshen_batch")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}